package com.mgy.im.standard;

import com.mgy.im.annotation.*;
import com.mgy.im.autoconfigure.NettyWebSocketProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * xxx
 *
 * @author maguoyong
 * @date 2020/6/14
 */
@Slf4j
public class NettyServerExporter extends ApplicationObjectSupport implements SmartInitializingSingleton, BeanFactoryAware {

    @Autowired
    private Environment environment;
    @Autowired
    private NettyWebSocketProperties properties;
    @Autowired
    private WebSocketHandler webSocketHandler;

    private BeanFactory beanFactory;


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void afterSingletonsInstantiated() {
        registerEndpoint();
    }


    private void registerEndpoint() {
        ApplicationContext context = getApplicationContext();
        if (context == null) {
            throw new RuntimeException("未获取到ApplicationContext");
        }
        Map<String, Object> beanMap = context.getBeansWithAnnotation(NettyWebSocket.class);
        if (beanMap == null || beanMap.size() == 0) {
            throw new RuntimeException("未发现注解NettyWebSocket");
        }
        if (beanMap.size() > 1) {
            throw new RuntimeException("发现多个类型被NettyWebSocket注解");
        }
        WebsocketServer websocketServer = new WebsocketServer(properties, webSocketHandler);
        try {
            websocketServer.start();
        } catch (Exception e) {
            log.error("启动失败", e);
        }
    }


}
